package com.example.j2eeapp.dao;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.util.Assert;

import com.example.j2eeapp.commons.dao.GenericJpaDao;
import com.example.j2eeapp.domain.UserEntity;

/**
 * 
 * Data Access Object interface to work with User entity database operations
 * 
 * @author cipherCata
 *
 */
//DAO pattern
public class UserJpaDao extends GenericJpaDao<UserEntity, Long> implements UserDao{

	public UserJpaDao() {
		super(UserEntity.class);
		
	}


	/**
	 * Queries database for user name availability
	 * 
	 * 
	 * @param userName
	 * @return true if the request username is available if not then throughs exception
	 */
	public boolean checkAvailable(String userName) {
		//check if userName is not empty if true then good if not then throw exception 
		Assert.notNull(userName);
		
		//create a var called query of type Query assign it the value of the username which is encapsulated by the EntityManager(handle entity context) which is used to create the query
		//to select from the class being persist to then get the user name and set the parameter to the userName.
		Query query = getEntityManager().createQuery("select count(*) from " + getPersistentClass().getSimpleName()
				+ "u where u.userName = :userName").setParameter("userName", userName);
		
		//returns the result
		Long count = (Long) query.getSingleResult();
		
		//if it returns less then 1 which = 0 then the username is available
		return count < 1;
	}

		
	/**
	 * 
	 * Queries user by username
	 * 
	 * @param userName
	 * @return User entity
	 */
	public UserEntity loadUserByUserName(String userName) {
		Assert.notNull(userName);
		
		//Initially the javabean has no value
		UserEntity user = null;
		
		//get username
		Query query = getEntityManager().createQuery("select u from " + getPersistentClass().getSimpleName()
				+ " u where u.userName = :userName").setParameter("userName", userName);
		
		try {
			user = (UserEntity) query.getSingleResult();
		} catch (NoResultException e) {
			// Do nothing
		}
		
		
		return user;
	}

}
